package main

import (
	"fmt"
	"gm/app/lib"
	"gm/app/model/model"
	"reflect"
	"sync"
	"time"
)

type Play_chatroom_nadd_captain struct {
	ID        int    `json:"id" gorm:"index"`
	Uid  string `json:"uid"`
}


/*速率相同切片多协程处理
 生产者，多消费者模式
*/
func main()  {
	t := time.Now()
	model.InitDB(lib.LoadServerConfig())
    ch :=make(chan Play_chatroom_nadd_captain,1)
    //新建一个生产者
	var wg sync.WaitGroup
	fmt.Println(reflect.TypeOf(wg))
	wg.Add(3)
    go producer(ch,&wg)
	// 主协程，模拟消费者，从channel读数据，打印到屏幕
	go consumer(ch,&wg) // 与 producer 传递的是同一个 channel
	go consumer(ch,&wg) // 与 producer 传递的是同一个 channel
	wg.Wait()

	fmt.Println("app done:", time.Since(t))

}

func producer(out chan<- Play_chatroom_nadd_captain,wg *sync.WaitGroup)  {

	defer func() {
		wg.Done()
		close(out)
	}()

	res,_:= get_active_conf()
	for _,v:=range res{
		out<- v
	}


}

// 此通道只能读，不能写
func consumer(in <-chan Play_chatroom_nadd_captain,wg *sync.WaitGroup) {
	defer func() {
		if err := recover() ; err != nil{
			fmt.Println(err)
		}
		wg.Done()
	}()
	for num := range in { // 从只读channel中获取数据
		time.Sleep(time.Second*1)
		fmt.Println(num)
	}
	panic("222")

}



func  get_active_conf() ([]Play_chatroom_nadd_captain, error) {
	var p []Play_chatroom_nadd_captain
	err := model.DB.Limit(10).Select("id,uid").Where(" type = ? ", 2).Find(&p).Error
	if err != nil {
		return nil, err
	}
	return p, nil
}

